<?php

namespace app\controllers;

use app\models\ArchiveLogs;
use app\models\Articles;
use app\models\CustomerServiceMessages;
use app\models\EnergyLogs;
use app\models\Orders;
use app\models\PayAccounts;
use app\models\Product;
use app\models\Task;
use app\models\Users;
use app\models\UsersProduct;
use app\services\AppointProductService;
use app\services\OrdersService;
use app\services\ProductService;
use app\services\UsersProductService;
use app\services\UsersService;
use app\services\UserTaskService;
use app\tools\T;
use Da\QrCode\QrCode;
use PHPUnit\Util\Filesystem;
use yii\db\Exception;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
use yii\web\UploadedFile;

class SiteController extends WebController {
    public function actionIndex() {
        $Users = \Yii::$app->user->identity;
        $ProductSer = new ProductService();
        $ProductSer->setParams('status', 1);
        $Products = $ProductSer->getAll();
        $AppointProduct = ArrayHelper::toArray($Users->appointProduct);
        $ProductIds = array_keys(array_column($AppointProduct, null, 'product_id'));

        $Data = [];
        foreach ($Products as $key => $product) {
            $Data[$key]['id'] = $product->id;
            $Data[$key]['name'] = $product->name;
            $Data[$key]['adoption_start_date'] = $product->adoption_start_date;
            $Data[$key]['adoption_end_date'] = $product->adoption_end_date;
            $Data[$key]['days'] = $product->days;
            $Data[$key]['earnings'] = $product->earnings;
            $Data[$key]['energy'] = $product->energy;
            $Data[$key]['un_app_energy'] = $product->un_app_energy;
            $Data[$key]['img_url'] = $product->img_url;
            $Data[$key]['max_num'] = $product->max_num;
            $Data[$key]['min_num'] = $product->min_num;
            if (in_array($product->id, $ProductIds)) {
                $Data[$key]['is_app'] = 1;
            } else {
                $Data[$key]['is_app'] = 0;
            }
        }
        return $this->render('index', ['Product' => $Data]);
    }

    public function actionTask() {
        $Task = Task::find()->where(['status' => 1])->all();
        $Users = \Yii::$app->user->identity;
        $UsersTask = $Users->userTask;
        $TaskId = array_keys(array_column($UsersTask, null, 'task_id'));
        $Data = [];
        foreach ($Task as $keys => $item) {
            $Data[$keys]['name'] = $item->name;
            $Data[$keys]['id'] = $item->id;
            $Data[$keys]['url'] = $item->url;
            $Data[$keys]['count'] = 0;
            if (in_array($item->id, $TaskId)) {
                $Data[$keys]['count'] = 1;
            }
        }
        return $this->render('task', ['Task' => $Data]);
    }

    public function actionTocomplate() {
        $Users = \Yii::$app->user->identity;
        $UsersTask = $Users->userTask;
        $TaskId = array_keys(array_column($UsersTask, null, 'task_id'));
        if (in_array($this->Params['task_id'], $TaskId)) {
            $this->outJson([], ERROR_CODE, '每天只能完成一次');
        }
        $UserTaskSer = new UserTaskService();
        $UserTaskSer->setTaskId($this->Params['id']);
        $UserTaskSer->setUserId($Users->id);
        $Users->energy_number = $Users->energy_number + 15;
        if ($UserTaskSer->addUserTask() && $Users->save()) {
            $EnergyLogs = new EnergyLogs();
            $EnergyLogs->type = 1;
            $EnergyLogs->num = 15;
            $EnergyLogs->user_id = $Users->id;
            $EnergyLogs->ctime = date("Y-m-d H:i:s");
            $EnergyLogs->save();
        }
        $Task = Task::findOne(['status' => 1, 'id' => $this->Params['id']]);
        return $this->render('detail', ['Task' => $Task]);
    }

    public function actionMyData() {
        return $this->render('my_data');
    }

    public function actionPromote() {
        $Users = \Yii::$app->user->identity;
        if (empty($Users->qrcode_text)) {
            $qrcode_str = "http://web.farmhappy.info/users/register?parent_invite_code=" . $Users->invite_code;
            $Qrcode = new QrCode($qrcode_str);
            $url = $Qrcode->useEncoding('UTF-8')->setSize(300)->setMargin(5)->writeDataUri();
            $config = [
                'image' => [
                    [
                        'url' => $url,
                        'stream' => 0,
                        'left' => 180,
                        'top' => 310,
                        'right' => 0,
                        'bottom' => 0,
                        'width' => 300,
                        'height' => 300,
                        'opacity' => 100,
                    ],
                ],
                'background' => 'http://app.mengzhuly.info/resource/picture/member/qrcode_mbae2b91c.png'                    //背景图
            ];
            $filename = time() . '.jpg';
            $randomFolder = date('Ymd');
            $savePath = '/uploads_bg/' . $randomFolder . '/' . $filename;
            $trueSavePath = \Yii::getAlias('@app/web') . $savePath;
            if (!Filesystem::createDirectory(dirname($trueSavePath))) {
                $this->outJson([], ERROR_CODE, '目录权限错误');
            }
            T::createPoster($config, $trueSavePath);
            $Users->qrcode_text = \Yii::$app->request->hostInfo . $savePath;
            $Users->save();
        }
        return $this->render('promote');
    }

    public function actionMyTeam() {
        $Users = \Yii::$app->user->identity;
        //第一代
        $FirstTeam = Users::find()->where(['parent_invite_code' => $Users->invite_code, 'status' => 1])->asArray()->all();
        foreach ($FirstTeam as $key => &$item) {
            $item['level'] = '第一代';
            $UsersProduct = UsersProduct::findOne(['user_id' => $item['id'], 'status' => [-1, 1, 2]]);
            if ($UsersProduct) {
                $item['activate'] = '已激活';
            } else {
                $item['activate'] = '待激活';
            }
            $item['grade'] = T::getLevel($item['energy_number']);
        }

        //第二代
        $parentInviteCode = [];
        $parentInviteCode = array_keys(array_column($FirstTeam, null, 'invite_code'));
        $SecondTeam = Users::find()->where(['parent_invite_code' => $parentInviteCode, 'status' => 1])->asArray()->all();
        foreach ($SecondTeam as $k => &$value) {
            $value['level'] = '第二代';
            $UsersProducts = UsersProduct::findOne(['user_id' => $value['id'], 'status' => [-1, 1, 2]]);
            if ($UsersProducts) {
                $value['activate'] = '已激活';
            } else {
                $value['activate'] = '待激活';
            }
            $value['grade'] = T::getLevel($value['energy_number']);
        }

        $MyTeam = array_merge($FirstTeam, $SecondTeam);
        $MyTeam = array_column($MyTeam, null, 'id');
        krsort($MyTeam);
        return $this->render('my_team', ['MyTeam' => $MyTeam]);
    }

    public function actionPayAccount() {
        return $this->render('pay_account');
    }

    public function actionDelAccount() {
        if (empty($this->Params['id'])) {
            $this->outJson([], ERROR_CODE, 'id为空');
        }

        $PayAccounts = PayAccounts::findOne(['user_id' => \Yii::$app->user->id, 'id' => $this->Params['id'], 'status' => [0, 1]]);
        if (empty($PayAccounts)) {
            $this->outJson([], ERROR_CODE, '没有该记录');
        }

        $PayAccounts->status = -1;
        $PayAccounts->utime = date("Y-m-d H:i:s");
        if ($PayAccounts->save()) {
            $this->outJson([], SUCCESS_CODE, '操作成功');
        } else {
            $this->outJson([], ERROR_CODE, '操作失败，请重试');
        }
    }

    public function actionAddAccountView() {
        return $this->render('add_account_view');
    }

    public function actionAjaxUpload() {
        $file = UploadedFile::getInstanceByName('file');
        if ($file->hasError) {
            $res['message'] = $file->error;
            $this->outJson([], ERROR_CODE, $file->error);
        }
        if (!$file->size) {
            $this->outJson([], ERROR_CODE, '文件内容是空的');
        }
        $allowTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp'];
        if (!in_array($file->type, $allowTypes)) {
            $this->outJson([], ERROR_CODE, '图片格式不正确');
        }
        // 验证文件格式
        if (!in_array($file->extension, ['jpg', 'gif', 'png', 'jpeg', 'bmp'])) {
            $this->outJson([], ERROR_CODE, '图片格式不正确');
        }
        // 验证文件大小
        if ($file->size >= 1024 * 1024 * 3) {
            $res['message'] = '图片大小超限[<=3mb]';
            $this->outJson([], ERROR_CODE, '图片大小超限[<=3mb]');
        }
        if ($file) {
            $randomNumber = microtime() . mt_rand(111111, 999999);
            $filename = md5($randomNumber) . '.' . $file->extension;
            $randomFolder = date('Ymd');
            $savePath = '/uploads_nj/' . $randomFolder . '/' . $filename;
            $trueSavePath = \Yii::getAlias('@app/web') . $savePath;
            if (!Filesystem::createDirectory(dirname($trueSavePath))) {
                $this->outJson([], ERROR_CODE, '目录权限错误');
            }
            if ($file->saveAs($trueSavePath)) {
                $this->outJson(['img_url' => \Yii::$app->request->hostInfo . $savePath], SUCCESS_CODE, '上传成功', '上传成功');
            } else {
                $this->outJson([], ERROR_CODE, $file->error);
            }
        }
    }

    public function actionAddPayAccount() {
        $Users = \Yii::$app->user->identity;
        $accounts = array_keys(array_column(ArrayHelper::toArray($Users->payAccount), null, 'type'));
        if (in_array($this->Params['type'], $accounts)) {
            $this->outJson([], ERROR_CODE, '已经添加过该类型的');
        }
        $PayAccount = new PayAccounts();
        $PayAccount->user_id = $Users->id;
        $PayAccount->type = $this->Params['type'];
        $PayAccount->account_number = $this->Params['account_number'];
        $PayAccount->real_name = $this->Params['real_name'];
        $PayAccount->mobile = $this->Params['mobile'];
        $PayAccount->alipay_img = $this->Params['alipay_img'] ?? '';
        $PayAccount->mark = $this->Params['mark'] ?? '';
        $PayAccount->ctime = date("Y-m-d H:i:s");
        $PayAccount->utime = date("Y-m-d H:i:s");
        $PayAccount->status = 0;
        if ($PayAccount->save()) {
            $this->outJson([], SUCCESS_CODE, '添加成功');
        } else {
            $this->outJson([], ERROR_CODE, '添加失败');
        }
    }

    public function actionPlatArticle() {
        $Article = Articles::find()->where(['status' => 2, 'type' => $this->Params['type']])->all();
        $title = '';
        if ($this->Params['type'] == 1) {
            $title = '平台公告';
        } else if ($this->Params['type'] == 2) {
            $title = '帮助中心';
        }
        return $this->render('plat_article', ['title' => $title, 'Article' => $Article]);
    }

    public function actionDetailArticle() {
        $Articles = Articles::findOne(['status' => 2, 'id' => $this->Params['id']]);
        return $this->render('detail_article', ['Articles' => $Articles]);
    }

    public function actionGetMyCustomer() {
        $Users = \Yii::$app->user->identity;
        $Customer = CustomerServiceMessages::find()
            ->where(['status' => 1])
            ->andWhere([
                'or',
                ['from_user_id' => $Users->id],
                ['to_user_id' => $Users->id],
            ])
            ->orderBy('id DESC')
            ->asArray()
            ->all();
        return $this->render('customer', ['Customer' => $Customer]);
    }

    public function actionSendCustomer() {
        return $this->render('send_customer');
    }

    public function actionAddCustomer() {
        $Users = \Yii::$app->user->identity;
        $Messages = new CustomerServiceMessages();
        $Messages->from_user_id = $Users->id;
        if (empty($this->Params['imgArr'])) {
            $this->outJson([], ERROR_CODE, '请上传图片');
        }
        $Messages->to_user_id = 0;
        $Messages->content = $this->Params['content'];
        $Messages->alt_image = isset($this->Params['imgArr'][0]) ? $this->Params['imgArr'][0] : '';
        $Messages->alt_image1 = isset($this->Params['imgArr'][1]) ? $this->Params['imgArr'][1] : '';
        $Messages->alt_image2 = isset($this->Params['imgArr'][2]) ? $this->Params['imgArr'][2] : '';
        $Messages->ctime = date("Y-m-d H:i:s");
        $Messages->status = 1;

        if (!$Messages->save()) {
            $this->outJson([], ERROR_CODE, '提交失败');
        } else {
            $this->outJson([], SUCCESS_CODE, '提交成功');
        }
    }

    public function actionAdoptedProduct() {
        $ProductSer = new ProductService();
        $ProductSer->setParams('id', $this->Params['id']);
        $ProductSer->setParams('status', 1);
        $Products = $ProductSer->getOne();
        if (empty($Products)) {
            $this->outJson([], ERROR_CODE, '没有该产品');
        }

        if (date("H:i:s") > $Products->adoption_end_date || date("H:i:s") < $Products->adoption_start_date) {
            $this->outJson([], ERROR_CODE, '请在领养期内领养');
        }

        $Users = \Yii::$app->user->identity;

        if(empty($Users->usersPayAccount)){
            $this->outJson([], ERROR_CODE, '请添加收款账户');
        }

        $UsersOrders = Orders::find()
            ->where(['buy_user_id' => $Users->id, 'product_id' => $Products->id])
            ->andWhere([
                'and',
                ['>=', 'ctime', date("Y-m-d 00:00:00")],
                ['<=', 'ctime', date('Y-m-d 23:59:59')],
            ])
            ->one();
        if (!empty($UsersOrders)) {
            $this->outJson([], ERROR_CODE, '您今天已经领养过该产品了，请明天再来吧');
        }
        //
        $UsersProductSer = new UsersProductService();
        $UsersProductSer->setParams('product_id', $Products->id);
        $UsersProductSer->setParams('status', 1);
        $UsersProductSer->setAndWhere([
            'and',
            ['<>', 'user_id', $Users->id],
//            ['>=', 'trad_date', date("Y-m-d 00:00:00")],
            ['<=', 'trad_date', date("Y-m-d 23:59:59")],
        ]);
        $UsersProduct = $UsersProductSer->getTimeByProduct();
        if (empty($UsersProduct)) {
            $this->outJson([], ERROR_CODE, '还没有可以领养的产品，请您耐心等待');
        }
        T::getRedis()->set('Product:Logs', Json::encode($UsersProduct));
        T::getRedis()->set('Product:Logs:Sellers', Json::encode($UsersProduct->users));
        T::getRedis()->set('Product:Logs:product', Json::encode($UsersProduct));
        $AppointProduct = ArrayHelper::toArray($Users->appointProduct);
        $AppointProductArr = array_keys(array_column($AppointProduct, null, 'product_id'));
        if (!in_array($Products->id, $AppointProductArr)) {
            if ($Users->energy_number < $Products->un_app_energy) {
                $this->outJson([], ERROR_CODE, '您的活力值不够');
            }
        }

        $OrdersSer = new OrdersService();
        $OrdersSer->setUsers($Users);
        $OrdersSer->setProduct($Products);
        if (!empty($UsersProduct)) {
            $OrdersSer->setSellersUsers($UsersProduct->users);
            $OrdersSer->setUsersProduct($UsersProduct);
        }

        $UsersProduct->status = 3;//锁定中
        $UsersProduct->utime = date("Y-m-d H:i:s");
        if ($OrdersSer->createOrders() && $UsersProduct->save()) {
            $this->outJson([], SUCCESS_CODE, '领养成功，请付款');
        } else {
            $this->outJson([], ERROR_CODE, '领养失败，请稍后再试');
        }
    }

    public function actionAppointProduct() {
        $ProductSer = new ProductService();
        $ProductSer->setParams('id', $this->Params['id']);
        $ProductSer->setParams('status', 1);
        $Products = $ProductSer->getOne();
        if (empty($Products)) {
            $this->outJson([], ERROR_CODE, '没有该产品');
        }

        if (date("H:i:s") > $Products->adoption_end_date) {
            $this->outJson([], ERROR_CODE, '生产中不能预约');
        }

        $Users = \Yii::$app->user->identity;
        if ($Users->energy_number < $Products->energy) {
            $this->outJson([], ERROR_CODE, '您的活力值不够');
        }

        $AppointProductSer = new AppointProductService();
        $AppointProductSer->setUsers($Users);
        $AppointProductSer->setProducts($Products);

        if ($AppointProductSer->addAppointProdcut()) {
            $this->outJson([], SUCCESS_CODE, '预约成功');
        } else {
            $this->outJson([], ERROR_CODE, '预约失败，请稍后再试');
        }
    }

    public function actionSetting() {
        return $this->render('setting');
    }

    public function actionLogout() {
        \Yii::$app->user->logout();
        return $this->goHome();
    }

    public function actionCheckHeadimg() {
        if (empty($this->Params['headimgurl'])) {
            $this->outJson([], ERROR_CODE, '请上传图片');
        }

        $Users = \Yii::$app->user->identity;
        $Users->headimgurl = $this->Params['headimgurl'];
        $Users->utime = date("Y-m-d H:i:s");
        if ($Users->save()) {
            $this->outJson([], SUCCESS_CODE, '操作成功');
        } else {
            $this->outJson([], ERROR_CODE, '操作失败');
        }
    }

    public function actionCheckUsername() {
        if (empty($this->Params['username'])) {
            $this->outJson([], ERROR_CODE, '请输入昵称');
        }
        $Users = \Yii::$app->user->identity;
        $Users->username = $this->Params['username'];
        $Users->utime = date("Y-m-d H:i:s");
        if ($Users->save()) {
            $this->outJson([], SUCCESS_CODE, '操作成功');
        } else {
            $this->outJson([], ERROR_CODE, '操作失败');
        }
    }

    public function actionEditPwd() {
        return $this->render('edit_pwd');
    }

    public function actionCheckPwd() {
        if (empty($this->Params['old_pwd'])) {
            $this->outJson([], ERROR_CODE, '请输入旧密码');
        }

        if (empty($this->Params['new_pwd'])) {
            $this->outJson([], ERROR_CODE, '请输入新密码');
        }

        $Users = \Yii::$app->user->identity;
        if ($Users->password != md5(sha1($this->Params['old_pwd']) . MENG_TOKEN)) {
            $this->outJson([], ERROR_CODE, '旧密码输入错误');
        }

        $Users->password = md5(sha1($this->Params['new_pwd']) . MENG_TOKEN);
        $Users->utime = date("Y-m-d H:i:s");
        if ($Users->save()) {
            $this->outJson([], SUCCESS_CODE, '操作成功');
        } else {
            $this->outJson([], ERROR_CODE, '操作失败');
        }
    }

    public function actionToEnergyNumber() {
        return $this->render('to_energy_number');
    }

    public function actionArchived() {
        $Users = \Yii::$app->user->identity;
        $ArchiveLogs = ArchiveLogs::find()->where(['user_id' => $Users->id, 'type' => $this->Params['type'], 'status' => 1])->orderBy('id DESC')->asArray()->all();
        return $this->render('archived', ['type' => $this->Params['type'], 'ArchiveLogs' => $ArchiveLogs]);
    }

    public function actionSellProduct() {
        $type = $this->Params['type'];
        $price = 0;
        $Product = Product::find()->where(['status' => 1])->asArray()->all();
        if ($type == 1) {
            $str = "转存收益";
            $price = \Yii::$app->user->identity->archived_earnings;
        } elseif ($type == 2) {
            $str = '推广收益';
            $price = \Yii::$app->user->identity->promotion_earnings;
        } else {
            $str = '团队收益';
            $price = \Yii::$app->user->identity->team_earnings;
        }
        return $this->render('sell_product', ['Product' => $Product, 'str' => $str, 'price' => $price, 'type' => $type]);
    }

    public function actionConfirmSell() {
        $Users = \Yii::$app->user->identity;

        $confirmSell = T::getRedis()->get('Usres:confirmSell:' . $keyDate . ':' . $this->Params['type'] . ':' . $Users->id);

        if (!empty($confirmSell)) {
            $this->outJson([], ERROR_CODE, '您今天已经出售过产品了');
        }

        $Product = Product::findOne(['status' => 1, 'id' => $this->Params['id']]);
        if (empty($Product)) {
            $this->outJson([], ERROR_CODE, '没有该产品');
        }

        $price = 0;
        switch ($this->Params['type']) {
            case 1:
                $price = $Users->archived_earnings;
                break;
            case 2:
                $price = $Users->promotion_earnings;
                break;
            case 3:
                $price = $Users->team_earnings;
                break;
        }

        if ($price < $Product->min_num) {
            $this->outJson([], ERROR_CODE, '您的余额不足');
        }

//        $date = date("H:i");
//        if ($date < '00:00' || $date > '12:00') {
//            $this->outJson([], ERROR_CODE, '现在不是出售时间');
//        }

        $tr = \Yii::$app->db->beginTransaction();
        try {

            switch ($this->Params['type']) {
                case 1:
                    $Users->archived_earnings = $Users->archived_earnings - (int)$Product->min_num;
                    break;
                case 2:
                    $Users->promotion_earnings = $Users->promotion_earnings - (int)$Product->min_num;
                    break;
                case 3:
                    $Users->team_earnings = $Users->team_earnings - (int)$Product->min_num;
                    break;
            }

            $UsersProductSer = new UsersProductService();
            $UsersProductSer->setParams('user_id', $Users->id);
            $UsersProductSer->setParams('product_id', $Product->id);
            $UsersProductSer->setParams('adopted_price', $Product->min_num);
            $earnings = ($Product->earnings + 100) / 100;//百分比
            $trad_price = $Product->min_num * $earnings;
            $UsersProductSer->setParams('trad_price', $trad_price);
            //总资产
            $Users->total_count = $Users->total_count + $trad_price;
            $Users->accumulated = $Users->accumulated + $trad_price - $Product->min_num;
            $toDay = date("Y-m-d");
            $UsersProductSer->setParams('trad_date', date("Y-m-d", strtotime("+" . $Product->days . " day", strtotime($toDay))) . ' ' . $Product->adoption_start_date);
            if (!$Users->save() || !$UsersProductSer->addUsersProdcut()) {
                $this->outJson([], ERROR_CODE, '出售失败');
            }
            $ArchiveLogs = new ArchiveLogs();
            $ArchiveLogs->user_id = $Users->id;
            $ArchiveLogs->price = '-' . $Product->min_num;
            $ArchiveLogs->order_id = 0;
            $ArchiveLogs->product_id = $Product->id;
            $ArchiveLogs->ctime = date("Y-m-d H:i:s");
            $ArchiveLogs->type = $this->Params['type'];
            if (!$ArchiveLogs->save()) {
                $this->outJson([], ERROR_CODE, '出售失败');
            }
            $tr->commit();
            T::getRedis()->set('Usres:confirmSell:' . $keyDate . ':' . $this->Params['type'] . ':' . $Users->id, $Users->id);
            $this->outJson([], SUCCESS_CODE, '出售成功');
        } catch (\Exception $exception) {
            $tr->rollBack();  // 回滚
            $this->outJson([], ERROR_CODE, $exception->getMessage());
        }
    }

    public function actionAdpot() {
        $Users = \Yii::$app->user->identity;
        $AppointProductSer = new AppointProductService();
        $AppointProductSer->setParams('status', 1);
        $AppointProductSer->setParams('user_id', $Users->id);
        $AppointProduct = $AppointProductSer->getAll();
        $Data = [];
        foreach ($AppointProduct as $k => $item) {
            $Data[$k]['product_name'] = $item->product->name;
            $Data[$k]['img_url'] = $item->product->img_url;
            $Data[$k]['ctime'] = $item->ctime;
            $Data[$k]['energy_number'] = $item->energy_number;
        }
        return $this->render('adpot', ['Data' => $Data]);
    }

    public function actionTrad() {
        $Users = \Yii::$app->user->identity;
        $Data = [];
        foreach ($Users->dealOrders as $key => $dealOrder) {
            $Data[$key]['order_sn'] = (string)$dealOrder->order_sn;
            $Data[$key]['product_name'] = (string)$dealOrder->product->name;
            $Data[$key]['img_url'] = $dealOrder->product->img_url;
            $Data[$key]['price'] = number_format($dealOrder->price, 2);
            $Data[$key]['ctime'] = $dealOrder->ctime;
            $Data[$key]['id'] = $dealOrder->id;
            $Data[$key]['status'] = $dealOrder->status;
        }
        return $this->render('trad', ['Data' => $Data]);
    }

    public function actionReadDetail() {
        $OrdersSer = new OrdersService();
        $OrdersSer->setParams('id', $this->Params['id']);
        $Orders = $OrdersSer->getOrderById();
        $Data = [];
        $Data['order_sn'] = $Orders->order_sn;
        $Data['ctime'] = $Orders->ctime;
        $Data['price'] = $Orders->price;
        $Data['img_url'] = $Orders->product->img_url;
        $Data['product_name'] = $Orders->product->name;
        $Data['mark'] = $Orders->mark;
        $Data['status'] = $Orders->status;
        $Data['trad_price'] = $Orders->usersProduct->trad_price;
        $Data['adopted_price'] = $Orders->usersProduct->adopted_price;
        $Data['new_time'] = date("Y-m-d H:i:s", strtotime("+20 minutes", strtotime($Orders->ctime)));

        if ($Orders->sellers_user_id) {
            $aliPay = PayAccounts::findOne(['status' => 1, 'type' => 2, 'user_id' => $Orders->sellers_user_id]);
            $bandCard = PayAccounts::findOne(['status' => 1, 'type' => 1, 'user_id' => $Orders->sellers_user_id]);
        } else {
            $aliPay = PayAccounts::findOne(['status' => 1, 'type' => 2, 'user_id' => 20]);
            $bandCard = PayAccounts::findOne(['status' => 1, 'type' => 1, 'user_id' => 20]);
        }
        $Data['aliPay'] = $aliPay;
        $Data['bandCard'] = $bandCard;
        return $this->render('read_detail', ['Data' => $Data, 'id' => $this->Params['id']]);
    }

    public function actionPayOrder() {
        if(empty($this->Params['mark'])){
            $this->outJson([], ERROR_CODE, '请上传交易图片');
        }
        $OrdersSer = new OrdersService();
        $OrdersSer->setParams('id', $this->Params['id']);
        $Orders = $OrdersSer->getOrderById();
        $Orders->mark = $this->Params['mark'];
        $Orders->status = 2;
        $Orders->utime = date("Y-m-d H:i:s");
        if ($Orders->save()) {
            $this->outJson([], SUCCESS_CODE, '提交成功');
        } else {
            $this->outJson([], ERROR_CODE, '提交失败，请重试');
        }
    }

    public function actionAppeal() {
        return $this->render('appeal', ['id' => $this->Params['id']]);
    }

    public function actionPayOrderComplaint() {
        $OrdersSer = new OrdersService();
        $OrdersSer->setParams('id', $this->Params['id']);
        $Orders = $OrdersSer->getOrderById();
        $Orders->buy_img = $this->Params['mark'];
        $Orders->status = 3;
        $Orders->mark_text = $this->Params['mark_text'];
        $Orders->utime = date("Y-m-d H:i:s");
        $Orders->initiator = \Yii::$app->user->identity->mobile;
        if ($Orders->save()) {
            $this->outJson([], SUCCESS_CODE, '提交成功');
        } else {
            $this->outJson([], ERROR_CODE, '提交失败，请重试');
        }
    }

    public function actionAppealList() {
        $Users = \Yii::$app->user->identity;
        $Data = [];
        foreach ($Users->complaintOrders as $key => $dealOrder) {
            $Data[$key]['mark_text'] = (string)$dealOrder->mark_text;
            $Data[$key]['mark'] = $dealOrder->mark;
            $Data[$key]['status'] = $dealOrder->status;
            $Data[$key]['id'] = $dealOrder->id;
        }
        return $this->render('appreal_list', ['Data' => $Data]);
    }

    public function actionMyProductList() {
        $Users = \Yii::$app->user->identity;
        /*
         * 类型
         * 1=全部    2  持有中    3交易中  4已转让
         * **/
        $Condition = [];
        $userProductIds = [];
        switch ($this->Params['type']) {
            case 2:
                $Condition['status'] = 1;
                break;
            case 3:
                $Condition['id'] = array_keys(array_column($Users->getSellerOrders()->asArray()->all(), null, 'users_product_id'));
                break;
            case 4:
                $Condition['status'] = 2;
        }


        $UsersProduct = $Users->getUsersProduct()->where($Condition)->orderBy('id DESC')->all();
        $Data = [];
        foreach ($UsersProduct as $key => $activeRecord) {
            $Data[$key]['product_name'] = $activeRecord->product->name;
            $Data[$key]['adopted_price'] = number_format($activeRecord->adopted_price, 2);
            $Data[$key]['ctime'] = $activeRecord->ctime;
            $Data[$key]['trad_date'] = $activeRecord->trad_date ?? '';
            $Data[$key]['energy_value'] = $activeRecord->energy_value;
            $Data[$key]['days'] = $activeRecord->product->days;
            $Data[$key]['earning'] = number_format($activeRecord->trad_price - $activeRecord->adopted_price, 2);
            $Data[$key]['trad_price'] = number_format($activeRecord->trad_price, 2);
            $Data[$key]['status'] = $activeRecord->status;
            $Data[$key]['statusStr'] = '';
            if ($Data[$key]['status'] == 1) {
                if (date("Y-m-d H:i:s") < $activeRecord->trad_date) {
                    $Data[$key]['statusStr'] = '持有中';
                } else {
                    $Data[$key]['statusStr'] = '待转让';
                }
            } else {
                $Data[$key]['statusStr'] = '已转让';
            }
        }
        return $this->render('my_product_list', ['Data' => $Data]);
    }

    public function actionTheHold() {
        $Users = \Yii::$app->user->identity;
        /*
         * 类型
         * 1=全部    2  持有中    3交易中  4已转让
         * **/
        $Condition = [];
        $Condition['status'] = 1;
        $UsersProduct = $Users->getUsersProduct()->where($Condition)->orderBy('id DESC')->all();
        $Data = [];
        foreach ($UsersProduct as $key => $activeRecord) {
            $Data[$key]['product_name'] = $activeRecord->product->name;
            $Data[$key]['adopted_price'] = number_format($activeRecord->adopted_price, 2);
            $Data[$key]['ctime'] = $activeRecord->ctime;
            $Data[$key]['trad_date'] = $activeRecord->trad_date ?? '';
            $Data[$key]['energy_value'] = $activeRecord->energy_value;
            $Data[$key]['days'] = $activeRecord->product->days;
            $Data[$key]['earning'] = number_format($activeRecord->trad_price - $activeRecord->adopted_price, 2);
            $Data[$key]['trad_price'] = number_format($activeRecord->trad_price, 2);
            $Data[$key]['status'] = $activeRecord->status;
            if ($Data[$key]['status'] == 1) {
                if (date("Y-m-d H:i:s") < $activeRecord->trad_date) {
                    $Data[$key]['statusStr'] = '持有中';
                } else {
                    $Data[$key]['statusStr'] = '待转让';
                }
            } else {
                $Data[$key]['statusStr'] = '已转让';
            }
        }
        return $this->render('the_hold', ['Data' => $Data]);
    }

    public function actionTradding() {
        $Users = \Yii::$app->user->identity;
        /*
         * 类型
         * 1=全部    2  持有中    3交易中  4已转让
         * **/
        $Condition = [];
        $userProductIds = [];
        $Condition['id'] = array_keys(array_column($Users->getSellerOrders()->asArray()->all(), null, 'users_product_id'));
        $UsersProduct = $Users->getUsersProduct()->where($Condition)->orderBy('id DESC')->all();
        $Data = [];
        foreach ($UsersProduct as $key => $activeRecord) {
            $Data[$key]['product_name'] = $activeRecord->product->name;
            $Data[$key]['adopted_price'] = number_format($activeRecord->adopted_price, 2);
            $Data[$key]['ctime'] = $activeRecord->ctime;
            $Data[$key]['trad_date'] = $activeRecord->trad_date ?? '';
            $Data[$key]['energy_value'] = $activeRecord->energy_value;
            $Data[$key]['days'] = $activeRecord->product->days;
            $Data[$key]['earning'] = number_format($activeRecord->trad_price - $activeRecord->adopted_price, 2);
            $Data[$key]['trad_price'] = number_format($activeRecord->trad_price, 2);
            $Data[$key]['status'] = $activeRecord->status;
        }
        return $this->render('tradding', ['Data' => $Data]);
    }

    public function actionAssigned() {
        $Users = \Yii::$app->user->identity;
        /*
         * 类型
         * 1=全部    2  持有中    3交易中  4已转让
         * **/
        $Condition = [];
        $userProductIds = [];
        $Condition['status'] = 2;
        $UsersProduct = $Users->getUsersProduct()->where($Condition)->orderBy('id DESC')->all();
        $Data = [];
        foreach ($UsersProduct as $key => $activeRecord) {
            $Data[$key]['product_name'] = $activeRecord->product->name;
            $Data[$key]['adopted_price'] = number_format($activeRecord->adopted_price, 2);
            $Data[$key]['ctime'] = $activeRecord->ctime;
            $Data[$key]['trad_date'] = $activeRecord->trad_date ?? '';
            $Data[$key]['energy_value'] = $activeRecord->energy_value;
            $Data[$key]['days'] = $activeRecord->product->days;
            $Data[$key]['earning'] = number_format($activeRecord->trad_price - $activeRecord->adopted_price, 2);
            $Data[$key]['trad_price'] = number_format($activeRecord->trad_price, 2);
            $Data[$key]['status'] = $activeRecord->status;
        }
        return $this->render('assigned', ['Data' => $Data]);
    }

    public function actionMyAssignment() {
        $Users = \Yii::$app->user->identity;
        $Data = [];
        foreach ($Users->sellerOrders as $key => $sellerOrder) {
            $Data[$key]['order_sn'] = $sellerOrder->order_sn;
            $Data[$key]['product_name'] = $sellerOrder->product->name;
            $Data[$key]['img_url'] = $sellerOrder->product->img_url;
            $Data[$key]['price'] = number_format($sellerOrder->price, 2);
            $Data[$key]['ctime'] = $sellerOrder->ctime;
            $Data[$key]['status'] = $sellerOrder->status;
            $Data[$key]['id'] = $sellerOrder->id;
        }
        return $this->render('my_assignment', ['Data' => $Data]);
    }

    public function actionMyComplate() {
        $Users = \Yii::$app->user->identity;
        $Data = [];
        foreach ($Users->sellerComplaintOrders as $key => $sellerOrder) {
            $Data[$key]['order_sn'] = $sellerOrder->order_sn;
            $Data[$key]['product_name'] = $sellerOrder->product->name;
            $Data[$key]['img_url'] = $sellerOrder->product->img_url;
            $Data[$key]['price'] = number_format($sellerOrder->price, 2);
            $Data[$key]['ctime'] = $sellerOrder->ctime;
            $Data[$key]['utime'] = $sellerOrder->utime;
            $Data[$key]['status'] = $sellerOrder->status;
            $Data[$key]['mark'] = $sellerOrder->mark;
            $Data[$key]['id'] = $sellerOrder->id;
        }
        return $this->render('my_complate', ['Data' => $Data]);
    }

    public function actionMyAppealData() {
        $Users = \Yii::$app->user->identity;
        $Data = [];
        foreach ($Users->sellerComplaintAppealOrders as $key => $dealOrder) {
            $Data[$key]['mark_text'] = (string)$dealOrder->mark_text;
            $Data[$key]['mark'] = $dealOrder->mark;
            $Data[$key]['status'] = $dealOrder->status;
            $Data[$key]['id'] = $dealOrder->id;
        }
        return $this->render('appeal_data', ['Data' => $Data]);
    }

    public function actionOrderInfo() {
        $OrdersSer = new OrdersService();
        $OrdersSer->setParams('id', $this->Params['id']);
        $Orders = $OrdersSer->getOrderById();
        $Data = [];
        $Data['order_sn'] = $Orders->order_sn;
        $Data['ctime'] = $Orders->ctime;
        $Data['price'] = $Orders->price;
        $Data['img_url'] = $Orders->product->img_url;
        $Data['product_name'] = $Orders->product->name;
        $Data['mark'] = $Orders->mark;
        $Data['status'] = $Orders->status;
        $Data['trad_price'] = $Orders->usersProduct->trad_price;
        $Data['adopted_price'] = $Orders->usersProduct->adopted_price;
        $Data['id'] = $Orders->id;
        $Data['new_time'] = date("Y-m-d H:i:s", strtotime("+20 minutes", strtotime($Orders->ctime)));

        if ($Orders->sellers_user_id) {
            $aliPay = PayAccounts::findOne(['status' => 1, 'type' => 2, 'user_id' => $Orders->sellers_user_id]);
            $bandCard = PayAccounts::findOne(['status' => 1, 'type' => 1, 'user_id' => $Orders->sellers_user_id]);
        } else {
            $aliPay = PayAccounts::findOne(['status' => 1, 'type' => 2, 'user_id' => 20]);
            $bandCard = PayAccounts::findOne(['status' => 1, 'type' => 1, 'user_id' => 20]);
        }
        $Data['aliPay'] = $aliPay;
        $Data['bandCard'] = $bandCard;
        return $this->render('order_info', ['Data' => $Data, 'id' => $Orders->id]);
    }

    public function actionConfirmOrder() {
        $OrdersSer = new OrdersService();
        $OrdersSer->setParams('id', $this->Params['id']);
        $Orders = $OrdersSer->getOrderById();

        $Users = \Yii::$app->user->identity;
        if ($Orders->sellers_user_id != $Users->id) {
            $this->outJson([], ERROR_CODE, '该订单不属于你');
        }

        if ($Orders->status != 2) {
            $this->outJson([], ERROR_CODE, '只有待确认订单可以确认');
        }

        if ($Orders->status == 4) {
            $this->outJson([], ERROR_CODE, '该订单已完成');
        }

        $tr = \Yii::$app->db->beginTransaction();  // 创建事务
        try {
            $UsersProductSer = new UsersProductService();
            $UsersProductSer->setParams('user_id', $Orders->buy_user_id);
            $UsersProductSer->setParams('product_id', $Orders->product_id);
            $UsersProductSer->setParams('adopted_price', $Orders->price);
            $earnings = ($Orders->product->earnings + 100) / 100;//百分比
            $archivedEarnings = $Orders->price * $earnings;//总价
            $trad_price = 0; //售价
            $trad_price = $archivedEarnings;
            if ($trad_price >= $Orders->product->max_num) {
                $UsersProductSer->setParams('type', 3);
            }

            //总资产
            $Orders->buyUser->total_count = $Orders->buyUser->total_count + $trad_price;
            if (!$Orders->buyUser->save()) {
                $error = array_values($Orders->buyUser->getFirstErrors())[0];
                throw new Exception($error);//抛出异常
            }

            $ArchiveLogs = new ArchiveLogs();
            $ArchiveLogs->user_id = $Orders->buyUser->id;
            $ArchiveLogs->price = $trad_price;
            $ArchiveLogs->order_id = $Orders->id;
            $ArchiveLogs->product_id = $Orders->product->id;
            $ArchiveLogs->ctime = date("Y-m-d H:i:s");
            $ArchiveLogs->type = 4;
            if (!$ArchiveLogs->save()) {
                $error = array_values($ArchiveLogs->getFirstErrors())[0];
                throw new Exception($error);//抛出异常
            }


            $UsersProductSer->setParams('trad_price', $trad_price);
            $date = date("Y-m-d");
            $UsersProductSer->setParams('trad_date', date("Y-m-d", strtotime("+" . $Orders->product->days . " day", strtotime($date))) . ' ' . $Orders->product->adoption_start_date);

            $Orders->status = 4;
            $Orders->utime = date("Y-m-d H:i:s");
            if (!$Orders->save()) {
                $error = array_values($Orders->getFirstErrors())[0];
                throw new Exception($error);//抛出异常
            }

            $Orders->usersProduct->status = 2;
            $Orders->usersProduct->utime = date("Y-m-d H:i:s");
            if (!$Orders->usersProduct->save()) {
                $error = array_values($Orders->usersProduct->getFirstErrors())[0];
                throw new Exception($error);//抛出异常
            }

            //累计收益
            $accumulated = 0;
            $accumulated = $trad_price - $Orders->price;
            $Users->total_count = $Users->total_count - $Orders->usersProduct->trad_price;
            if (!$Users->save()) {
                $error = array_values($Users->getFirstErrors())[0];
                throw new Exception($error);//抛出异常
            }

            $ArchiveLogs = new ArchiveLogs();
            $ArchiveLogs->user_id = $Users->id;
            $ArchiveLogs->price = '-'.$Orders->usersProduct->trad_price;
            $ArchiveLogs->order_id = $Orders->id;
            $ArchiveLogs->product_id = $Orders->product->id;
            $ArchiveLogs->ctime = date("Y-m-d H:i:s");
            $ArchiveLogs->type = 4;
            if (!$ArchiveLogs->save()) {
                $error = array_values($ArchiveLogs->getFirstErrors())[0];
                throw new Exception($error);//抛出异常
            }



            $Orders->buyUser->accumulated = $Orders->buyUser->accumulated + $accumulated;
            if (!$Orders->buyUser->save()) {
                $error = array_values($Orders->buyUser->getFirstErrors())[0];
                throw new Exception($error);//抛出异常
            }

            $ArchiveLogs = new ArchiveLogs();
            $ArchiveLogs->user_id = $Orders->buyUser->id;
            $ArchiveLogs->price = $accumulated;
            $ArchiveLogs->order_id = $Orders->id;
            $ArchiveLogs->product_id = $Orders->product->id;
            $ArchiveLogs->ctime = date("Y-m-d H:i:s");
            $ArchiveLogs->type = 5;
            if (!$ArchiveLogs->save()) {
                $error = array_values($ArchiveLogs->getFirstErrors())[0];
                throw new Exception($error);//抛出异常
            }


            if (!$UsersProductSer->addUsersProdcut()) {
                throw new Exception('UsersProductSer add error');//抛出异常
            }

            /*
             * 推广收益
             * **/
            //第一代
            $UsersSer = new UsersService();
            $UsersSer->setParams('invite_code', $Orders->buyUser->parent_invite_code);
            $FirstUsers = $UsersSer->getOne();
            if ($FirstUsers) {
                $FirstUsers->promotion_earnings = $FirstUsers->promotion_earnings + ($accumulated * 10 / 100);
                $FirstUsers->utime = date("Y-m-d H:i:s");
                if ($FirstUsers->save()) {
                    $ArchiveLogs = new ArchiveLogs();
                    $ArchiveLogs->user_id = $FirstUsers->id;
                    $ArchiveLogs->price = ($accumulated * 10 / 100);
                    $ArchiveLogs->order_id = $Orders->id;
                    $ArchiveLogs->product_id = $Orders->product->id;
                    $ArchiveLogs->ctime = date("Y-m-d H:i:s");
                    $ArchiveLogs->type = 2;
                    if (!$ArchiveLogs->save()) {
                        $error = array_values($ArchiveLogs->getFirstErrors())[0];
                        throw new Exception($error);//抛出异常
                    }
                }

                //第二代
                $UsersSer = new UsersService();
                $UsersSer->setParams('invite_code', $FirstUsers->parent_invite_code);
                $SecondUsers = $UsersSer->getOne();
                if ($SecondUsers) {
                    $SecondUsers->promotion_earnings = $SecondUsers->promotion_earnings + ($accumulated * 5 / 100);
                    $SecondUsers->utime = date("Y-m-d H:i:s");
                    if ($SecondUsers->save()) {
                        $ArchiveLogs = new ArchiveLogs();
                        $ArchiveLogs->user_id = $SecondUsers->id;
                        $ArchiveLogs->price = ($accumulated * 5 / 100);
                        $ArchiveLogs->order_id = $Orders->id;
                        $ArchiveLogs->product_id = $Orders->product->id;
                        $ArchiveLogs->ctime = date("Y-m-d H:i:s");
                        $ArchiveLogs->type = 2;
                        if (!$ArchiveLogs->save()) {
                            $error = array_values($ArchiveLogs->getFirstErrors())[0];
                            throw new Exception($error);//抛出异常
                        }
                    }
                }
            }

            //团队收益
            $FirstTeams = Users::findOne(['invite_code' => $Orders->buyUser->parent_invite_code, 'status' => 1]);
            if (!empty($FirstTeams)) {
                if ($FirstTeams->promotion_earnings > 100) {
                    $FirstTeams->team_earnings = $FirstTeams->team_earnings + ($accumulated * 2 / 100);
                    $FirstTeams->utime = date("Y-m-d H:i:s");
                    if ($FirstTeams->save()) {
                        $ArchiveLogs = new ArchiveLogs();
                        $ArchiveLogs->user_id = $FirstTeams->id;
                        $ArchiveLogs->price = ($accumulated * 2 / 100);
                        $ArchiveLogs->order_id = $Orders->id;
                        $ArchiveLogs->product_id = $Orders->product->id;
                        $ArchiveLogs->ctime = date("Y-m-d H:i:s");
                        $ArchiveLogs->type = 3;
                        if (!$ArchiveLogs->save()) {
                            $error = array_values($ArchiveLogs->getFirstErrors())[0];
                            throw new Exception($error);//抛出异常
                        }
                    }
                }

                //上上级
                $SecondTeams = Users::findOne(['invite_code' => $FirstTeams->parent_invite_code, 'status' => 1]);
                if ($SecondTeams->promotion_earnings >= 100) {
                    $SecondTeams->team_earnings = $SecondTeams->team_earnings + ($accumulated * 2 / 100);
                    $SecondTeams->utime = date("Y-m-d H:i:s");
                    if ($SecondTeams->save()) {
                        $ArchiveLogs = new ArchiveLogs();
                        $ArchiveLogs->user_id = $SecondTeams->id;
                        $ArchiveLogs->price = ($accumulated * 2 / 100);
                        $ArchiveLogs->order_id = $Orders->id;
                        $ArchiveLogs->product_id = $Orders->product->id;
                        $ArchiveLogs->ctime = date("Y-m-d H:i:s");
                        $ArchiveLogs->type = 3;
                        if (!$ArchiveLogs->save()) {
                            $error = array_values($ArchiveLogs->getFirstErrors())[0];
                            throw new Exception($error);//抛出异常
                        }
                    }
                }
            }

            $tr->commit();  //
            $this->outJson([], SUCCESS_CODE, '确认成功');
        } catch (\Exception $exception) {
            $tr->rollBack();  // 回滚
            T::getRedis()->set('Orders:Confirm:' . date("Ymd") . ":" . $Orders->id, $exception->getMessage());
            $this->outJson([], ERROR_CODE, $exception->getMessage());
        }
    }
}
